package com.xyy.saas.payment.adapter.channel;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.xyy.saas.payment.adapter.ChannelSettingManager;
import com.xyy.saas.payment.adapter.PaymentAdapter;
import com.xyy.saas.payment.manage.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.pojo.dto.PayDto;
import com.xyy.saas.payment.exception.PaymentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zhangwenxiong
 * @Date 2021/1/13 15:13
 * @Version 1.0
 */
@Component
public class AliCommonAdapter implements PaymentAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliCommonAdapter.class);

    @Autowired
    private ChannelSettingManager channelSettingManager;

    public String getBill(PayDto payDto) throws Exception{
        LOGGER.info("AliCommonAdapter getBill begin payDto:{}", JSON.toJSONString(payDto));
        try {
            AlipayClient client = channelSettingManager.getAlipayClient(payDto.getBusinessOrderType(), payDto.getPayMode());
            AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
            model.setBillType("trade");
            model.setBillDate(payDto.getMap().get("billDate").toString());
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            request.setBizModel(model);
            AlipayDataDataserviceBillDownloadurlQueryResponse response = client.execute(request);
            if (response.isSuccess()) {
                return response.getBillDownloadUrl();
            } else {
                LOGGER.error("AliCommonAdapter#getBill response not success payDto:{} response:{}", JSONUtils.toJSONString(payDto), JSONUtils.toJSONString(response));
                if(response.getSubMsg().contains("余额不足")) {
                    throw new PaymentException(ResultCodeEnum.CHANNEL_TODAY_MONEY_NOT_ENOUGH);
                }else {
                    LOGGER.error("AliCommonAdapter#refund create failed refundDto:{},result:{}", JSON.toJSONString(payDto), JSON.toJSONString(response));
                    throw new PaymentException(ResultCodeEnum.CHANNEL_CONNECT_ERROR);
                }
            }
        }catch (Exception e){
            LOGGER.error("AliCommonAdapter#refund create failed refundDto:{}", JSON.toJSONString(payDto), e);
            throw new PaymentException(ResultCodeEnum.CHANNEL_CONNECT_ERROR);
        }
    }

}
